package com.cy.jwt;

import io.jsonwebtoken.*;
import org.junit.Test;

import java.util.Date;
import java.util.UUID;

/**
 * @title: JwtTest
 * @Author Luo
 * @Date: 2021/7/16 上午 09:31
 * @Version 1.0
 */
public class JwtTests {

    private static long tokenExpiration = 1000;//1000 * 60 * 60 * 24;
    private static String tokenSignKey = "cy123456";

    @Test
    public void testCreatedToken() {
        JwtBuilder jwtBuilder = Jwts.builder();
        //头,载荷,签名哈希
        String jwtToken = jwtBuilder
                //头
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")

                //载荷:自定义信息
                .claim("nickname", "Helen")
                .claim("avatar", "1,png")
                .claim("role", "admin")

                //载荷:默认信息
                .setSubject("xrd-user") //令牌主题
                .setIssuer("cy")    //签发者
                .setAudience("cy")  //接收方
                .setIssuedAt(new Date())    //令牌的签发时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))  //过期时间
                .setNotBefore(new Date(System.currentTimeMillis() + 1000 * 20)) //生效时间
                .setId(UUID.randomUUID().toString())

                //签名哈希
                .signWith(SignatureAlgorithm.HS256, tokenSignKey)

                //组装jwt字符串
                .compact();
        System.out.println(jwtToken);
    }

    @Test
    public void testGetUserInfo() {
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuaWNrbmFtZSI6IkhlbGVuIiwiYXZhdGFyIjoiMSxwbmciLCJyb2xlIjoiYWRtaW4iLCJzdWIiOiJ4cmQtdXNlciIsImlzcyI6ImN5IiwiYXVkIjoiY3kiLCJpYXQiOjE2MjY0MDYzNTgsImV4cCI6MTYyNjQwNjM1OSwibmJmIjoxNjI2NDA2Mzc4LCJqdGkiOiJhZmM5NWUzZS0zYzEzLTQwODEtOGMyYi0xZThmNzIyYWViYmUifQ.SUN7ahuts1zVxcwTDAYKRf6ZgIqk_zIdIuN2kTkyzCs";
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(tokenSignKey).parseClaimsJws(token);

        Claims claims = claimsJws.getBody();

        String nickname = (String) claims.get("nickname");
        String avatar = (String) claims.get("avatar");
        String role = (String) claims.get("role");
        System.out.println(nickname);
        System.out.println(avatar);
        System.out.println(role);

        String id = claims.getId();
        System.out.println(id);


    }
}

















